package cotrollor;

import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8"); // 告诉服务器如何解析请求，解析请求里面的body为utf8
        resp.setCharacterEncoding("utf8"); // 返回响应告诉浏览器解析为utf8
        // 1.获取登录页面用户输入的信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || username.equals("") || password == null || password.equals("")) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前用户名或密码为空");
            return;
        }
        System.out.println(username + " : " + password);
        // 2.查询数据库，看用户信息是否正确
        UserDao userDao = new UserDao();
        User user = userDao.select(username);
        if (user == null) {
            // 用户为空,不存在该用户
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("您的用户名或密码错误");
            return;
        }
        if (!password.equals(user.getPassword())) {
            // 用户密码错误
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("您的用户名或密码错误");
            return;
        }
        // 3.登录成功,构造会话
        HttpSession session = req.getSession(true);
        // 把刚刚获取的user对象放入会话中，方便后续使用
        session.setAttribute("user", user);
        // 4.返回重定向报文，跳转到博客列表页
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 验证登录状态
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setStatus(403);
            return;
        }
        User user = (User)session.getAttribute("user");
        if (user == null) {
            resp.setStatus(403);
            return;
        }
        // 已登录
        resp.setStatus(200);
    }
}
